import { addDishApi, getDishDetailApi, updateDishApi } from "@/api/dish";
import { useCatetory } from "@/hooks/useCatetory";
import { useUserStore } from "@/stores/user";
import { AddDishData, FlavorItem } from "@/types/dish";
import { message } from "@/utils/AntdGlobal";
import { PlusOutlined } from "@ant-design/icons";
import { Card, FormProps, InputNumber, Upload, UploadFile, UploadProps } from "antd";
import TextArea from "antd/es/input/TextArea";


export function Component() {
  const { Option } = Select;
  // 获取表单
  const [form] = Form.useForm();
  const navigate = useNavigate();
  // 获取传过来的id
  const [params] = useSearchParams();
  const dishId = params.get('id')
  // 获取菜品分类
  const { categoryList } = useCatetory()
  const onFinish: FormProps<AddDishData>['onFinish'] = async (values) => {
    if (dishId) {
      await updateDishApi({
        categoryId: values.categoryId,
        description: values.description,
        image: fileList[0].url! || fileList[0].response.data,
        name: values.name,
        price: values.price,
        flavors: defaultValue!,
        id: +dishId
      })
      message.success('修改成功')
    } else {
      await addDishApi({
        categoryId: values.categoryId,
        description: values.description,
        image: fileList[0].response.data,
        name: values.name,
        price: values.price,
        flavors: defaultValue!
      })
      message.success('添加成功')
    }
    navigate(-1)
  };
  interface Option {
    value?: string | number | null;
    label: React.ReactNode;
    children?: Option[];
    isLeaf?: boolean;
  }
  // 获取路由
  useEffect(() => {
    const getDishDetail = async () => {
      const res = await getDishDetailApi(+dishId!)
      form.setFieldsValue({
        ...res.data,
        flavors: parseJsonToArray(res.data.flavors)
      })
      // 回显图片
      setFileList([{
        uid: '',
        name: '',
        url: res.data.image
      }])
      console.log(res);

    }
    if (dishId) {
      getDishDetail()
    }
  }, [])
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList);
  }
  /**
   * 口味做法配置
   */
  // 定义口味列表
  const flavourList = [
    {
      id: 1,
      label: "忌口",
      value: "忌口",
      children: [
        {
          label: "不要葱",
          value: "不要葱",
        },
        {
          label: "不要蒜",
          value: "不要蒜",
        }, {
          label: "不要香菜",
          value: "不要香菜",
        },
        {
          label: "不要辣",
          value: "不要辣",
        }
      ]
    },
    {
      id: 2,
      label: "温度",
      value: "温度",
      children: [
        {
          label: "热饮",
          value: "热饮",
        },
        {
          label: "常温",
          value: "常温",
        }, {
          label: "去冰",
          value: "去冰",
        },
        {
          label: "少冰",
          value: "少冰",
        },
        {
          label: "多冰",
          value: "多冰",
        }
      ]
    },
    {
      id: 3,
      label: "甜味",
      value: "甜味",
      children: [
        {
          label: "无糖",
          value: "无糖",
        },
        {
          label: "少糖",
          value: "少糖",
        }, {
          label: "半糖",
          value: "半糖",
        },
        {
          label: "多糖",
          value: "多糖",
        },
        {
          label: "全糖",
          value: "全糖",
        }
      ]
    },
    {
      id: 4,
      label: "辣度",
      value: "辣度",
      children: [
        {
          label: "不辣",
          value: "不辣",
        },
        {
          label: "微辣",
          value: "微辣",
        }, {
          label: "中辣",
          value: "中辣",
        },
        {
          label: "重辣",
          value: "重辣",
        },
      ]
    },
  ]
  const [options] = useState<Option[]>(flavourList);
  // 口味的默认值
  const [defaultValue, setDefaultValue] = useState<FlavorItem[]>()
  // 改变口味
  // const changeFlavour = (data: string[]) => {
  //   const arr = flavourList.reduce((prev: FlavorItem[], item) => {
  //     if (data.includes(item.label)) {
  //       prev.push({
  //         name: item.label,
  //         value: JSON.stringify(item.children.map(v => v.label))
  //       })
  //     }
  //     return prev
  //   }, [])
  //   setDefaultValue(arr)
  // }
  const parseJsonToArray = (data: { id?: number; dishId?: number; name: string; value: string }[]): [string, string][] => {
    const result: [string, string][] = [];

    data.forEach(item => {
      try {
        const values = JSON.parse(item.value) as string[];
        values.forEach(value => {
          result.push([item.name, value]);
        });
      } catch (error) {
        console.error(`Error parsing JSON for item ${item.id}:`, error);
      }
    });

    return result;
  }

  const transformData = (data: [string, string][]): { name: string; value: string }[] => {
    const result: Record<string, string[]> = {};

    data.forEach(([category, value]) => {
      if (!result[category]) {
        result[category] = [];
      }
      result[category].push(value);
    });

    // 将对象转换为数组
    const transformedArray = Object.keys(result).map(category => ({
      name: category,
      value: JSON.stringify(result[category])
    }));

    return transformedArray;
  }

  const onChange = (data: any) => {
    const arr = transformData(data)
    setDefaultValue(arr)
  };
  return (
    <div style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
      {/* 查询 */}
      <Card className="mb-4" size="small">
        <div className="flex flex-justify-between flex-items-center">
          <div className="font-bold font-size-4">{dishId ? '修改菜品' : '添加菜品'}</div>
          <Button type="primary" onClick={() => navigate(-1)}>
            返回
          </Button>
        </div>
      </Card>
      {/* 表格 */}
      <Card style={{ overflow: 'auto', height: '100%' }}>
        <div className="flex flex-justify-center">
          <Form
            name="basic"
            form={form}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            style={{ minWidth: 800 }}
            initialValues={{ sex: '1' }}
            onFinish={onFinish}
            autoComplete="off"
          >
            <Form.Item<AddDishData>
              label="菜品名称"
              name="name"
              rules={[{ required: true, message: '请输入菜品名称!' }]}
            >
              <Input placeholder="请输入菜品名称" />
            </Form.Item>

            <Form.Item<AddDishData> name="categoryId" label="菜品分类" rules={[{ required: true, message: '请输入菜品价格!' }]}>
              <Select
                placeholder="请选择菜品分类"
                allowClear
              >
                {categoryList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
              </Select>
            </Form.Item>

            <Form.Item<AddDishData>
              label="菜品价格"
              name="price"
              rules={[{ required: true, message: '请输入菜品价格!' }]}
            >
              <InputNumber style={{ width: "100%" }} min={0} max={10000} placeholder="请输入菜品价格" />
            </Form.Item>
            <Form.Item<AddDishData> label="口味做法配置" name="flavors">
              {/* <Select
                placeholder="口味"
                allowClear
                mode="multiple"
                style={{ width: "100%" }}
                onChange={(value) => changeFlavour(value)}
              >
                {flavourList.map(item => <Option key={item.id} value={item.value}>{item.label}</Option>)}
              </Select> */}
              <Cascader options={options} placeholder="套餐菜品" multiple maxTagCount={"responsive"} showCheckedStrategy="SHOW_CHILD" onChange={onChange} changeOnSelect />
            </Form.Item>
            <Form.Item label="菜品图片" name="image" rules={[{ required: true, message: '请上传图片!' }]}>
              <Upload
                action={"http://localhost:9000/api/admin/common/upload"}
                listType="picture-card"
                maxCount={1}
                accept="image/*"
                name="file"
                fileList={fileList}
                onChange={handleChange}
                headers={{ token: useUserStore.getState().token }}
              >
                <button style={{ border: 0, background: 'none' }} type="button">
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传图片</div>
                </button>
              </Upload>
            </Form.Item>
            <Form.Item<AddDishData>
              label="菜品描述"
              name="description"
            >
              <TextArea rows={4} placeholder="请输入菜品描述" />
            </Form.Item>
            <Form.Item wrapperCol={{ span: 24 }}>
              <div className="flex flex-justify-center mr-8">
                <Button type="default" onClick={() => navigate(-1)} className="mr-8">
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  {dishId ? "修改" : '添加'}
                </Button>
              </div>
            </Form.Item>
          </Form>
        </div>
      </Card >
    </div >
  )
}